import axios from '../config/axios'
import { hostname } from '../config/host.config'
import Router from 'next/router'
import { message } from 'antd'

export const userState = {
    username: '',
    userImg: '',
    loginStatus: 0
}

export const actionTypes = {
    loginIn: 'loginIn',
    loginOut: 'loginOut'
}

export const UserReducer = (state = userState, action) => {
    switch (action.type) {
        case actionTypes.loginIn:
            return Object.assign({}, state, {
                username: action.username,
                userImg: action.userImg,
                loginStatus: 2
            })
        case actionTypes.loginOut:
            return Object.assign({}, state, {
                username: '',
                userImg: '',
                loginStatus: 1
            })
        default:
            return state
    }
}

export const userLoginIn = ({ account, password }) => async dispatch => {
    const res = await axios.post(hostname + '/login', {
        'account': account,
        'password': password
    })
    if (res.status === 200 && res.data.statusCode === 1) {
        dispatch({
            type: actionTypes.loginIn,
            username: res.data.statusMag.username,
            userImg: res.data.statusMag.imageUrl
        })
        message.success('登录成功')
        Router.push('/index')
    } else {
        dispatch({
            type: actionTypes.loginOut
        })
        message.error('账户或密码错误')
    }
}

export const getUserInfo = () => async dispatch => {
    try {
        const res = await axios.get(hostname + '/login/userInfo')
        if (res.status === 200 && res.data.statusCode === 1) {
            dispatch({
                type: actionTypes.loginIn,
                username: res.data.statusMag.username,
                userImg: res.data.statusMag.imageUrl
            })
            return true
        } else {
            dispatch({
                type: actionTypes.loginOut
            })
            return false
        }
    } catch (err) {
        dispatch({
            type: actionTypes.loginOut
        })
        return false
    }
}

export const setLoginInfo = () => dispatch => {
    return dispatch({
        type: actionTypes.loginOut
    })
}

export const loginOut = () => async dispatch => {
    const res = await axios.post(hostname + '/login/Out')
    if (res.status === 200 && res.data.statusCode === 1) {
        message.success('退出成功')
        Router.push('/')
        dispatch({
            type: actionTypes.loginOut
        })
    } else {
        message.error('出错了 请重试!')
    }
}

export const register = async ({ account, password, email }) => {
    const res = await axios.post(hostname + '/users/new', { account, password, email })
    if (res.status === 200 && res.data.statusCode === 1) {
        message.success('注册成功')
        Router.push('/')
    } else {
        message.error(res.data.statusMsg)
    }
}
